package ua.org.nuos.sdms.clientgui.client.handlers;

import ua.org.nuos.sdms.clientgui.client.context.Messages;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.ChangeCurrentGroupEvent;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.ChangeCurrentGroupListener;
import ua.org.nuos.sdms.clientgui.client.util.ComponentUtil;
import ua.org.nuos.sdms.clientgui.client.view.selectGroup.SelectGroupWindow;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;
import ua.org.nuos.sdms.middle.entity.User;
import ua.org.nuos.sdms.middle.util.exception.UpdateEntityException;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 06.03.12
 * Time: 19:42
 * To change this template use File | Settings | File Templates.
 */
public class ChangeCurrentGroupHandler implements ChangeCurrentGroupListener {
    @Override
    public void change(ChangeCurrentGroupEvent event) {
        try {
            Group g = event.getGroup();
            User user = AppProxy.getInstance().getServiceLocator().getAuthenticationBean().getCurrentUser();
            user.setLastGroup(g);
            AppProxy.getInstance().getServiceLocator().getClientBean().updateCurrentUser(user);
            AppProxy.getInstance().getModelLocator().setGroup(g);
            ComponentUtil.closeWindow(SelectGroupWindow.ID);
        } catch (UpdateEntityException e) {
            Logger.getAnonymousLogger().log(Level.WARNING, "Cant change group", e);
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.ACTION_ERROR));
        } catch (Exception e) {
            Logger.getAnonymousLogger().log(Level.WARNING, "Cant change group", e);
            AppProxy.getInstance().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.ACTION_ERROR));
        }
    }
}
